package com.herench.bunch.exam.convert;


import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.QRY_Q01;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.QRD;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.alibaba.fastjson.JSON;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExamApplicationConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Map<String, Object> toMessage(RequestMessage requestMessage) throws Exception {
        Map<String, Object> resMap = new HashMap<String, Object>();

        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    resMap.put(temp[0],temp[1]);
                }
            }
        }
        logger.info(requestMessage.getMsgCode() + " params :"+ resMap);
        return resMap;
    }

    @Override
    Map<String, Object> doToMessage(RequestMessage requestMessage) throws Exception {
        return null;
    }


    @Override
    public Message fromMessage(Object message) throws Exception {
        Assert.notNull(message, "message 为空.");
        List<Map<String,Object>> resList = (List<Map<String, Object>>) JSON.parse(message.toString());

        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);
        MSA msa = rtbK13.getMSA();
        if (resList.size()>0){
            msa.getErrorCondition().getCe1_Identifier().setValue("0");
            msa.getErrorCondition().getCe2_Text().setValue("成功");
        }else {
            msa.getErrorCondition().getCe1_Identifier().setValue("-1");
            msa.getErrorCondition().getCe2_Text().setValue("无数据");
        }

        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();

        int index = 0;

        for (int i = 0;i<resList.size();i++){
            RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
            CE ce = new CE(rtbK13);
            ce.getCe1_Identifier().setValue("RD");
            StringBuffer buffer = new StringBuffer();
            buffer.append("examNo=").append(resList.get(i).get("examNo")).append("#")
                    .append("examClass=").append(resList.get(i).get("examClass")).append("#")
                    .append("name=").append(resList.get(i).get("name")).append("#")
                    .append("ywm=").append(resList.get(i).get("ywm")).append("#")
                    .append("sex=").append(resList.get(i).get("sex")).append("#")
                    .append("age=").append(resList.get(i).get("age")).append("#")
                    .append("dateOfBirth=").append(resList.get(i).get("dateOfBirth")).append("#")
                    .append("medicalNo=").append(resList.get(i).get("medicalNo")).append("#")
                    .append("patientSource=").append(resList.get(i).get("patientSource")).append("#")
                    .append("patientId=").append(resList.get(i).get("patientId")).append("#")
                    .append("reqDept=").append(resList.get(i).get("reqDept")).append("#")
                    .append("reqPhysician=").append(resList.get(i).get("reqPhysician")).append("#")
                    .append("itemName=").append(resList.get(i).get("itemName")).append("#")
                    .append("examBui=").append(resList.get(i).get("examBui")).append("#")
                    .append("costs=").append(resList.get(i).get("costs")).append("#")
                    .append("charges=").append(resList.get(i).get("charges")).append("#")
                    .append("examDateTime=").append(resList.get(i).get("examDateTime")).append("#")
                    .append("visitId=").append(resList.get(i).get("visitId")).append("#")
                    .append("clinDiag=").append(resList.get(i).get("clinDiag")).append("#")
                    .append("reqDeptCode=").append(resList.get(i).get("reqDeptCode")).append("#")
                    .append("reqDeptInput=").append(resList.get(i).get("reqDeptInput")).append("#")
                    .append("reqDoctCode=").append(resList.get(i).get("reqDoctCode")).append("#")
                    .append("reqDoctInput=").append(resList.get(i).get("reqDoctInput")).append("#")
                    .append("itemInput=").append(resList.get(i).get("itemInput")).append("#")
                    .append("itemCode=").append(resList.get(i).get("itemCode")).append("#")
                    .append("cardNo=").append(resList.get(i).get("cardNo")).append("#")
                    .append("examBui2=").append(resList.get(i).get("examBui2")).append("#")
                    .append("examBui2Code=").append(resList.get(i).get("examBui2Code")).append("#")
                    .append("urgentSign=").append(resList.get(i).get("urgentSign")).append("#")
                    .append("patId=").append(resList.get(i).get("patId")).append("#")
                    .append("visId=").append(resList.get(i).get("visId"));
            ce.getCe2_Text().setValue(buffer.toString());
            rdt.getColumnValue().setData(ce);
            definition.insertRDT(rdt, index++);
        }
        return rtbK13;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_Q01 qry = new QRY_Q01();
        qry.initQuickstart("QRY_Q01", "Q01", "A");
        MSH msh = qry.getMSH();
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("300020");
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMsh7_DateTimeOfMessage().getTs1_TimeOfAnEvent().setValue(new Date());
        msh.getMsh10_MessageControlID().setValue(IdGenerator.getUUID());
        QRD qrd = qry.getQRD();

        int index = 0;
        qrd.insertQrd8_WhoSubjectFilter(index++).getXcn16_NameContext().getCe2_Text().setValue("4246178257441441008");
        qrd.insertQrd8_WhoSubjectFilter(index++).getXcn16_NameContext().getCe2_Text().setValue("001");
        qrd.insertQrd8_WhoSubjectFilter(index++).getXcn16_NameContext().getCe2_Text().setValue("1");
        qrd.insertQrd8_WhoSubjectFilter(index++).getXcn16_NameContext().getCe2_Text().setValue("010201");


        return qry;

    }
}
